using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Dynamic;
using YTS.Tools;

namespace Test.ConsoleProgram.Algorithm.Work
{
    [TestDescription("工作逻辑: 枚举转换")]
    public class Test_EnumHelper : AbsBaseTestItem
    {
        [AttributeUsage(AttributeTargets.All)]
        public class EnumDescriptionAttribute : DescriptionAttribute
        {
            public EnumDescriptionAttribute(string description) : base(description) { }
        }
        public enum SetDic
        {
            [EnumDescription("订单状态")]
            OrderStatus = 1,

            [EnumDescription("日志操作人类型")]
            LogOperPersonType = 5,

            [EnumDescription("活动进度")]
            ActivityStatue = 23,
        }

        public override void OnTest()
        {
            Assert.TestExe<Func<SetDic, string, int, SetDic>, SetDic[]>(
                ToEnumList<SetDic, SetDic>,
                (e, name, vint) => e,
                equalsMethod: (i1, i2) => i1.ToJSONString() == i2.ToJSONString(),
                new SetDic[] { SetDic.OrderStatus, SetDic.LogOperPersonType, SetDic.ActivityStatue });

            Assert.TestExe<Func<SetDic, string, int, string>, string[]>(
                ToEnumList<SetDic, string>,
                (e, name, vint) => e.GetEnumAttributeValue<SetDic, EnumDescriptionAttribute, string>(m => m.Description),
                equalsMethod: (i1, i2) => i1.ToJSONString() == i2.ToJSONString(),
                new string[] { "订单状态", "日志操作人类型", "活动进度" });
        }

        public static M[] ToEnumList<E, M>(Func<E, string, int, M> toModelFunc) where E : struct
        {
            System.Type type = typeof(E);
            if (!type.IsEnum)
            {
                return new M[] { };
            }
            List<M> list = new List<M>();
            foreach (int ival in System.Enum.GetValues(type))
            {
                string name = System.Enum.GetName(type, ival);
                if (System.Enum.TryParse<E>(name, out E v))
                {
                    list.Add(toModelFunc(v, name, ival));
                }
            }
            return list.ToArray();
        }
    }
}
